import QRCode from 'qrcode';
import Qs from 'qs';
import router from '@/router';


//验证手机号  宽松模式--只要是1开头即可
export const isMobile = mobile => /^(?:(?:\+|00)86)?1\d{10}$/.test(mobile)


//push模式打开新页面
export const Open = (path) => path && router.push(path)


//replace模式打开新页面
export const replace = (path, query) => {
    path && router.replace({
        path,
        query
    })
}


//格式化
export const QaString = params => {
    const Qsquery = Qs.stringify(params)
    const query = Qsquery ? `?${Qsquery}` : ""
    return query
}


//判断是否是微信环境
export const isWeChat = () => (/micromessenger/i).test(navigator.userAgent)


//判断是否是手机环境
export const isPC = () => {
    const u = navigator.userAgent
    return !u.match(/AppleWebKit.*Mobile.*/)
}


//创建二维码
export const createCode = url => {
    return new Promise((resolve, reject) => {
        QRCode.toDataURL(url,{
            width: 500,
        }, (err, newUrl) => {
            if(!err) {
                resolve([false, newUrl])
            }
            else {
                resolve([true, null])
            }
        });
    })
}


//回到顶部
export const backTop = (y = 0) => {
    function scrollTop() {
        const distance = document.documentElement.scrollTop || document.body.scrollTop;
        if(distance > y) {
            window.requestAnimationFrame(scrollTop);
            // setTimeout(scrollTop, 20);
            window.scrollTo(y, distance - distance / 6);
        }
    }
    scrollTop();
}




